package com.gdufe.studytogether.service.comment.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gdufe.studytogether.domain.R;
import com.gdufe.studytogether.domain.pojo.Comment;
import com.gdufe.studytogether.domain.pojo.Competition;
import com.gdufe.studytogether.domain.pojo.User;
import com.gdufe.studytogether.mapper.CommentMapper;
import com.gdufe.studytogether.service.comment.CommentService;
import com.gdufe.studytogether.service.competition.CompetitionService;
import com.gdufe.studytogether.service.user.UserService;
import com.gdufe.studytogether.utils.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CommemtServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {
    @Autowired
    CommentMapper commentMapper;
    @Autowired
    CompetitionService competitionService;
    @Autowired(required = false)
    private RedisTemplate redisTemplate;

    @Autowired
    UserService userServiceImpl;
    @Override
    public R listComment(Long pageSize,Long pageCurrent,Integer competitionId,User user,String com) {
        Page<Comment> page = new Page<>();
        if (pageSize==null){
            pageSize=20L;
        }
        if (pageCurrent==null){
            pageCurrent=1L;
        }
        page.setCurrent(pageCurrent);
        page.setSize(pageSize);
        QueryWrapper<Comment> qw = new QueryWrapper<>();
        Integer uid=null;
        if(user!=null){
            uid=user.getId();
        }
        qw.eq("parentid",0);//只查一级评论
        if (competitionId!=null&&competitionId!=-1){
            qw.eq("cid",competitionId);
        }
        qw.eq("cmStatus",1);//只查看审核通过的
        if (!StringUtils.isEmpty(com)&&!com.equals("null")){
            qw.like("content",com);
        }
        qw.orderByDesc("createTime");
        Page<Comment> page1 = this.page(page, qw);
        List<Comment> records = page1.getRecords();
        for (Comment comment : records) {
            User cuser = userServiceImpl.getById(comment.getUid());
            comment.setUsername(cuser.getUsername());
            comment.setImg(cuser.getImg());
            boolean isLike = checkIsLike(comment.getId(), uid);
            comment.setIslike(isLike);
        }
        return R.ok(page1);
    }


    public R getCommentsByParentId(Long pageSize,Long pageCurrent,Integer id,User user){
        Page<Comment> page = new Page<>();
        if(pageSize==null){
            pageSize=10L;
        }
        if(pageCurrent==null){
            pageCurrent=1L;
        }
        page.setCurrent(pageCurrent);
        page.setSize(pageSize);
        Integer uid=null;
        if (user!=null){
            uid= user.getId();
        }
        QueryWrapper<Comment> qw = new QueryWrapper<>();
        qw.eq("parentid",id);
        qw.orderByDesc("cmLike").orderByDesc("createTime");
        Page<Comment> page1 = this.page(page, qw);
        List<Comment> records = page1.getRecords();
        for (Comment comment : records) {
            User cuser = userServiceImpl.getById(comment.getUid());
            comment.setUsername(cuser.getUsername());
            comment.setImg(cuser.getImg());
            boolean isLike = checkIsLike(comment.getId(), uid);
            comment.setIslike(isLike);
        }
        return R.ok(page1);
    }



    @Override
    public R addComment(Comment comment) throws Exception {
        //检查比赛是否存在
        Integer parentId = comment.getParentId();
        if(parentId==null){

            Integer cid = comment.getCid();
            if(cid!=null){
                R r = competitionService.selectById(cid);
                if (r.getData()==null||!"0".equals(((Competition)r.getData()).getStatus())){
                    throw new Exception("比赛不存在");
                }
            }else {
                throw new Exception("请选择参与的竞赛");
            }
            comment.setParentId(0);
        }

        if (StringUtils.isEmpty(comment.getContent())){
            throw new Exception("请输入评论内容");
        }
        if(comment.getParentId()==null&&StringUtils.isEmpty(comment.getTitle())){
            throw new Exception("请输入标题");
        }

        Integer uid = UserThreadLocal.get();
        comment.setUid(uid);
        if (redisTemplate==null){
            comment.setCmStatus(1);
        }else{
            comment.setCmStatus(0);
        }
        comment.setCreateTime(LocalDateTime.now());
        comment.setCommentCount(0);
        comment.setCmLike(0);
        boolean save = this.save(comment);
        if (!save){
            throw new Exception("添加评论失败");
        }

        if (parentId!=null){
            //更新评论数
            commentMapper.addCommentCount(parentId);
        }

        if (redisTemplate!=null){
            //添加到redis
            ListOperations listOperations = redisTemplate.opsForList();
            listOperations.leftPush("comments",comment.getId()+"/@/#/@/"+comment.getContent());
        }
        return R.ok(null);
    }

    @Override
    public R deleteComment(Integer id) throws Exception {
        Integer uid = UserThreadLocal.get();
        Comment c = this.getById(id);
        if (!c.getUid().equals(uid)){
            throw new Exception("无法删除其他人的评论");
        }
        boolean b = this.removeById(id);
        if (!b){
            throw new Exception("删除失败");
        }
        return R.ok(null);
    }

    @Override
    public R likeComment(Integer id) throws Exception {
        if(id==null){
            throw new Exception("评论不存在");
        }
        Integer uid = UserThreadLocal.get();
        if (uid==null){
            throw new Exception("未登录，请登录后重新尝试");
        }
        Comment comment = getById(id);
        if (comment==null){
            throw new Exception("评论不存在");
        }

        commentMapper.addCommentLike(uid,id);
        commentMapper.addLikeCount(id,1);
        return R.ok();
    }

    @Override
    public R unlikeComment(Integer id) throws Exception {
        if(id==null){
            throw new Exception("评论不存在");
        }
        Integer uid = UserThreadLocal.get();
        if (uid==null){
            throw new Exception("未登录，请登录后重新尝试");
        }
        Comment comment = getById(id);
        if (comment==null){
            throw new Exception("评论不存在");
        }

        commentMapper.deleteCommentLike(uid,id);
        commentMapper.addLikeCount(id,-1);
        return R.ok();
    }

    //检查是否已经点赞，cid:评论id
    private boolean checkIsLike(Integer cid,Integer uid){
        Integer count = commentMapper.getIsCommentLike(uid, cid);
        if (uid==null){
            return false;
        }
        if (count>0){
            return true;
        }
        return false;
    }
}
